package com.itheima.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.interceptors.LoginInterceptor;
import com.itheima.mapper.ArticleMapper;
import com.itheima.pojo.Article;
import com.itheima.pojo.ArticleQueryParam;
import com.itheima.pojo.Category;
import com.itheima.pojo.PageBean;
import com.itheima.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.HashSet;
import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public Article addArticle(Article article) {
        article.setCreateUser(LoginInterceptor.curUser.get().getId());
        articleMapper.addArticle(article);
        return article;
    }

    @Override
    public PageBean<Article> list(Integer pageNum,
                                  Integer pageSize,
                                  @RequestParam(required = false) Integer categoryId,
                                  @RequestParam(required = false) String  state) {
        // 1. 创建PageBean对象
        PageBean<Article> pb = new PageBean<>();
        PageHelper.startPage(pageNum, pageSize);

        List<Article> as = articleMapper.list(LoginInterceptor.curUser.get().getId(), categoryId, state);
        System.out.println("这里搜索出的文章列表数量为" + as.size());
        Page<Article> p = (Page<Article>) as;

        // 2. 开启分页查询
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());

        return pb;
    }

    @Override
    public Article getDetail(Integer id) {
        Article article = articleMapper.getDetailById(id);
        return article;
    }

    @Override
    public Article updateArticle(Article article) {
        Article art = getDetail(article.getId());
        BeanUtil.copyProperties(article, art, CopyOptions.create().setIgnoreNullValue(true));
        articleMapper.updateArticle(art);
        return art;
    }

    @Override
    public void deleteArticle(Integer id) {
        articleMapper.deleteArticle(id);
    }
}
